# -*- coding: utf-8 -*-
#######################################################################################
#                                                                                     #
#    File: Core.py                                                                 #
#    Part of stage1st_cheater                                                         #
#    Home: http://stage1st-cheater.googlecode.com                                     #
#                                                                                     #
#    The MIT License                                                                  #
#                                                                                     #
#    Copyright (c) 2010-2011 <araya.akashic@gmail.com>                                #
#                                                                                     #
#    Permission is hereby granted, free of charge, to any person obtaining a copy     #
#    of this software and associated documentation files (the "Software"), to deal    #
#    in the Software without restriction, including without limitation the rights     #
#    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell        #
#    copies of the Software, and to permit persons to whom the Software is            #
#    furnished to do so, subject to the following conditions:                         #
#                                                                                     #
#    The above copyright notice and this permission notice shall be included in       #
#    all copies or substantial portions of the Software.                              #
#                                                                                     #
#    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR       #
#    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,         #
#    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE      #
#    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER           #
#    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,    #
#    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN        #
#    THE SOFTWARE.                                                                    #
#                                                                                     #
#######################################################################################
'''
Created on May 22, 2011

@author: flyxian
'''
import operator

from PyQt4.QtCore import *
from PyQt4.QtGui import *

from MainDialog import *

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s
    
class MainWindow(QMainWindow, Ui_MainDialog):
    write_account_signal = pyqtSignal()
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        '''user defined'''
        self.pushButton_online_keeper_start.state = False
        
        self.createActions()
        self.createTrayIcon()
        self.trayIcon.show()

        self.trayIcon.setVisible(True)
        
        icon = QtGui.QIcon(_fromUtf8("./images/logo.png"))
        self.setWindowIcon(icon)
    
#    def setVisible(self, visible):
#        self.minimizeAction.setEnabled(visible)
#        self.maximizeAction.setEnabled(not self.isMaximized())
#        self.restoreAction.setEnabled(self.isMaximized() or not visible)
#        super(MainWindow, self).setVisible(visible)
    
    def closeEvent(self, event):
        if self.trayIcon.isVisible():
#            QMessageBox.information(self, "Systray",
#                    _fromUtf8("The program will keep running in the system tray. To "
#                    "terminate the program, choose <b>退出</b> in the "
#                    "context menu of the system tray entry."))
            self.hide()
            event.ignore()
        else:
            qApp.quit()
            
    def createActions(self):
        self.minimizeAction = QAction(_fromUtf8("最小化"), self,
                                            triggered=self.hide)
#        self.maximizeAction = QAction("Ma&ximize", self,
#                                            triggered=self.showMaximized)
        self.restoreAction = QAction(_fromUtf8("还原"), self,
                                           triggered=self.showNormal)
        self.quitAction = QAction(_fromUtf8("退出"), self,
                                        triggered=qApp.quit)
                    
    def createTrayIcon(self):
        icon = QIcon(_fromUtf8("./images/logo.png"))
#        icon.addPixmap(QPixmap(_fromUtf8(":/images/trash.svg")), 
#                       QIcon.Normal, QtGui.QIcon.Off)
        self.trayIconMenu = QMenu(self)
        self.trayIconMenu.addAction(self.minimizeAction)
#        self.trayIconMenu.addAction(self.maximizeAction)
        self.trayIconMenu.addAction(self.restoreAction)
        self.trayIconMenu.addSeparator()
        self.trayIconMenu.addAction(self.quitAction)

        self.trayIcon = QSystemTrayIcon(icon, self)
        self.trayIcon.setContextMenu(self.trayIconMenu)    
        
    def init_display_properties(self):
        self.online_keeper_account_list.setColumnHidden(1, True)
        
    def online_keeper_account_list_reset(self):
        self.online_keeper_account_list.reset()
        self.online_keeper_account_list.setColumnHidden(1, True)
        
        
    def init_signals(self):
        #backgrounds
        QObject.connect(self.online_keeper_dataModel,
                        SIGNAL(_fromUtf8("dataChanged()")),
                        self.online_keeper_account_list_reset)
        #operations
        QObject.connect(self.online_keeper_account_list, 
                        SIGNAL(_fromUtf8("clicked(QModelIndex)")), 
                        self.online_keeper_get_selection)
        QObject.connect(self.pushButton_online_keeper_add,
                        SIGNAL(_fromUtf8("clicked()")), 
                        self.online_keeper_set_account)
        QObject.connect(self.pushButton_online_keeper_del,
                        SIGNAL(_fromUtf8("clicked()")), 
                        self.online_keeper_del_account)
#        QObject.connect(self.pushButton_online_keeper_start,
#                        SIGNAL(_fromUtf8("clicked()")),
#                        self.online_keeper_start)

        
#    def online_keeper_add_account(self):
#        username = self.

    def online_keeper_get_selection(self):
        indexlist = self.online_keeper_account_list.selectionModel().selectedIndexes()
        datamodel = self.online_keeper_account_list.model()

        self.online_keeper_username.setText(datamodel.data(indexlist[0]).toString())
        self.online_keeper_passwd.setText(datamodel.data(indexlist[1]).toString())
        
    def online_keeper_set_account(self):
        indexlist = self.online_keeper_account_list.selectionModel().selectedIndexes()
        datamodel = self.online_keeper_account_list.model()
#        print indexlist
        if len(indexlist) > 0:
            datamodel.setData(indexlist[0], self.online_keeper_username.text())
            datamodel.setData(indexlist[1], self.online_keeper_passwd.text())
        else:
            if len(self.online_keeper_username.text()) == 0\
                or len(self.online_keeper_passwd.text()) == 0:
                return
            else:
                if not datamodel.insertRows(datamodel.rowCount(), 1):
                    return
                child = datamodel.index(datamodel.rowCount()-1, 0)
                datamodel.setData(child, self.online_keeper_username.text(), Qt.EditRole)
                child = datamodel.index(datamodel.rowCount()-1, 1)
                datamodel.setData(child, self.online_keeper_passwd.text(), Qt.EditRole)
                child = datamodel.index(datamodel.rowCount()-1, 2)
                datamodel.setData(child, _fromUtf8('##'), Qt.EditRole)
                
                self.online_keeper_username.clear()
                self.online_keeper_passwd.clear()
            
        self.write_account_signal.emit()
    
    def online_keeper_del_account(self):
        indexlist = self.online_keeper_account_list.selectionModel().selectedIndexes()
        model = self.online_keeper_account_list.model()
        if len(indexlist) <= 0:
            return
        else:
            model.removeRow(indexlist[0].row())
            self.online_keeper_username.clear()
            self.online_keeper_passwd.clear()
            
        self.write_account_signal.emit()
            

                
    def online_keeper_start(self):
        if self.pushButton_online_keeper_start.state:
            self.pushButton_online_keeper_start.state = False
            self.online_keeper_account_list.setDisabled(False)
            self.online_keeper_passwd.setDisabled(False)
            self.online_keeper_username.setDisabled(False)
            self.pushButton_online_keeper_add.setDisabled(False)
            self.pushButton_online_keeper_cancel.setDisabled(False)
            self.pushButton_online_keeper_del.setDisabled(False)
        else:
            self.pushButton_online_keeper_start.state = True
            self.online_keeper_account_list.setDisabled(True)
            self.online_keeper_passwd.setDisabled(True)
            self.online_keeper_username.setDisabled(True)
            self.pushButton_online_keeper_add.setDisabled(True)
            self.pushButton_online_keeper_cancel.setDisabled(True)
            self.pushButton_online_keeper_del.setDisabled(True)
        
        
        
#online_keeper_account_list
    def update_online_keeper_account_list(self, tabledata):
        header = [_fromUtf8('用户名'), '',  _fromUtf8('运行状态')]
        self.online_keeper_dataModel = OnlineKeeper_AccountListModel(tabledata, header)
        self.online_keeper_account_list.setModel(self.online_keeper_dataModel)
    

        
class OnlineKeeper_AccountListModel(QAbstractTableModel): 
    def __init__(self, datain, headerdata, parent=None, *args): 
        """ datain: a list of lists
            headerdata: a list of strings
        """
        super(OnlineKeeper_AccountListModel, self).__init__(parent)
        self.arraydata = datain
        self.headerdata = headerdata
 
    def rowCount(self, parent=QModelIndex()): 
        return len(self.arraydata) 
 
    def columnCount(self, parent=QModelIndex()): 
        try:
            return len(self.arraydata[0])
        except:
            return 0
 
    def data(self, index, role=Qt.DisplayRole): 
        if not index.isValid(): 
            return QVariant() 
        elif role != Qt.DisplayRole: 
            return QVariant() 
        return QVariant(self.arraydata[index.row()][index.column()]) 

    def headerData(self, col, orientation, role):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return QVariant(self.headerdata[col])
        return QVariant()
    
    def setData(self, index, value, role=Qt.EditRole):
        try:
            self.arraydata[index.row()][index.column()] = value
#            print self.arraydata
            self.emit(SIGNAL(_fromUtf8("dataChanged()")))
            return True
        except:
            print "Model.setData == False"
            return False
        
    def insertRows(self, position, rows, parent=QModelIndex()):
        self.beginInsertRows(parent, position, position + rows - 1)
        self.arraydata.append([_fromUtf8(''), _fromUtf8(''), False])
        self.endInsertRows()
        return True
    
    def removeRows(self, position, rows, parent=QModelIndex()):
        self.beginRemoveRows(parent, position, position + rows - 1)
        del(self.arraydata[position])
        self.endRemoveRows()
        return True
        

if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    window = MainWindow()

    window.show()

    sys.exit(app.exec_())